import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '../stores/user';
import type { RouteLocationNormalized, NavigationGuardNext } from 'vue-router';
import HomeView from '../views/HomeView.vue';
import LoginRegister from '../views/LoginRegister.vue';
import Article from '../views/Article.vue';
import ArticleDetail from '../views/ArticleDetail.vue';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'new-home',
      component: HomeView
    },
    {
      path: '/loginregister',
      name: 'loginregister',
      component: LoginRegister
    },
    {
      path: '/article',
      name: 'article',
      component: Article
    },
    {
      path: '/articledetail',
      name: 'articledetail',
      component: ArticleDetail
    }
  ]
});

router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
  const userStore = useUserStore();
  if (to.name === 'todolist' && !userStore.isAuthenticated) {
    next({ name: 'login' });
  } else {
    next();
  }
});

export default router;